use crate::utils::rgb_to_hsv;
use image::RgbImage;

pub fn check_background(img: &RgbImage) -> Result<String, String> {
    let (width, height) = (img.width(), img.height());
    let mut samples = Vec::new();

    // 采样边缘10%区域像素
    let edge_width = width / 10;
    let edge_height = height / 10;

    // 上边缘
    for y in 0..edge_height {
        for x in 0..width {
            let pixel = img.get_pixel(x, y);
            samples.push(rgb_to_hsv(pixel.0[0], pixel.0[1], pixel.0[2]));
        }
    }

    // 下边缘
    for y in (height - edge_height)..height {
        for x in 0..width {
            let pixel = img.get_pixel(x, y);
            samples.push(rgb_to_hsv(pixel.0[0], pixel.0[1], pixel.0[2]));
        }
    }

    // 左边缘
    for y in edge_height..(height - edge_height) {
        for x in 0..edge_width {
            let pixel = img.get_pixel(x, y);
            samples.push(rgb_to_hsv(pixel.0[0], pixel.0[1], pixel.0[2]));
        }
    }

    // 右边缘
    for y in edge_height..(height - edge_height) {
        for x in (width - edge_width)..width {
            let pixel = img.get_pixel(x, y);
            samples.push(rgb_to_hsv(pixel.0[0], pixel.0[1], pixel.0[2]));
        }
    }

    if samples.is_empty() {
        return Err("无法采样背景像素".to_string());
    }

    // 判断蓝色背景 (H:100-130, S:43-100, V:46-100)
    let blue_count = samples
        .iter()
        .filter(|&&(h, s, v)| h >= 100.0 && h <= 130.0 && s >= 43.0 && v >= 46.0)
        .count();

    // 判断白色背景 (H:0-180, S:0-30, V:85-100)
    let white_count = samples
        .iter()
        .filter(|&&(_h, s, v)| s <= 30.0 && v >= 85.0)
        .count();

    let total = samples.len();
    match (blue_count * 5 > total * 3, white_count * 5 > total * 3) {
        (true, _) => Ok("蓝色背景".to_string()),
        (_, true) => Ok("白色背景".to_string()),
        _ => Err(format!(
            "背景颜色不符合要求 (蓝色像素: {}%, 白色像素: {}%)",
            blue_count * 100 / total,
            white_count * 100 / total
        )),
    }
}
